<?php

namespace app\admin\validate;

use app\common\Validate;
use app\model\Admin;

class AdminValidate extends Validate
{
    /**
     * 验证规则
     */
    protected $rule = [
        "rid" => ["require", "checkRidMin:"],
        "name" => ["require", "length" => "2,12"],
        "avatar" => ["require"],
        "username" => ["require", "length" => "6,12", "alphaDash", "uniqueUser:"],
        "password" => ["requirePwd:", "length" => "6,18", "alphaDash"],
        "oldPwd" => ["require", "isPwd:"],
        "newPwd" => ["require", "length" => "6,18", "alphaDash"],
        "verifyPwd" => ["require", "confirm:newPwd"],
    ];
    /**
     * 提示消息
     */
    protected $message = [
        "rid.require" => "请选择角色",
        "rid.checkRidMin" => "非法数据",
        'name.length' => '长度必须在2-12之间',
        'name.require' => '不能为空',
        "avatar.require" => "不能为空",
        'username.require' => '不能为空',
        'username.alphaDash' => '只能包含字母、数字、下划线和破折号',
        'username.length' => '长度必须在6-12之间',
        "username.uniqueUser" => "用户名已存在",
        'password.requirePwd' => '不能为空',
        'password.alphaDash' => '只能包含字母、数字、下划线和破折号',
        'password.length' => '长度必须在6-18之间',
        "oldPwd.require" => '不能为空',
        "oldPwd.isPwd" => '旧密码错误',
        'newPwd.require' => '不能为空',
        'newPwd.alphaDash' => '只能包含字母、数字、下划线和破折号',
        'newPwd.length' => '长度必须在6-18之间',
        'verifyPwd.require' => '不能为空',
        'verifyPwd.confirm' => '两次输入的密码不一致'
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => ["rid", "name", "avatar", "username", "password"],
        'edit' => ["rid", "name", "avatar", "username", "password"],
        'basicsInfo' => ["name", "avatar", "username"],
        'editPwd' => ["oldPwd", "newPwd", "verifyPwd"]
    ];

    // 自定义验证用户名
    protected function uniqueUser($value)
    {
        $all = request()->param();
        $w = [["username", "=", $value]];
        if (isset($all["id"])) {
            $find = Admin::find($all["id"]);
            if ($value == $find["username"]) {
                $w[] = [["id", "<>", $find["id"]]];
            }
        }
        $Username = Admin::where($w)->find();
        if ($Username) {
            return false;
        } else {
            return true;
        }
    }

    // 自定义验证密码
    protected function requirePwd($value)
    {
        $all = request()->param();
        if (!isset($all["id"])) {
            if ($value == "") {
                return false;
            }
        }
        return true;
    }

    // 自定义验证角色不能为0
    protected function checkRidMin($value)
    {
        return ($value != '0' && $value !== '');
    }

    //自定义验证仅密码
    protected function isPwd($value)
    {
        $User = session('user');
        if (password_verify($value, $User["password"])) {
            return true;
        } else {
            return false;
        }
    }
}
